using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public class RechargeForm : Form
    {
        private Panel headerPanel;
        private Panel mainPanel;
        private Panel bottomPanel;
        
        // 当前用户信息
        private string cardNo;
        private int currentUserId;
        private string currentUserName;
        
        // 充值信息
        private Label lblCardNo;
        private Label lblCurrentBalance;
        private TextBox txtRechargeAmount;
        private ComboBox cmbPayChannel;
        private Button btnRecharge;
        private Button btnCancel;
        
        // 充值结果
        private Label lblResult;

        public RechargeForm(string cardNo, int userId, string userName)
        {
            this.cardNo = cardNo;
            this.currentUserId = userId;
            this.currentUserName = userName;
            InitializeComponent();
            SetupEventHandlers();
            LoadCardInfo();
        }

        private void InitializeComponent()
        {
            // 设置窗体基本属性
            this.Size = new Size(500, 400);
            this.Text = "医疗卡充值";
            this.StartPosition = FormStartPosition.CenterParent;
            this.BackColor = UIStyleManager.BackgroundColor;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建头部面板
            headerPanel = new Panel
            {
                Size = new Size(500, 60),
                BackColor = UIStyleManager.PrimaryColor,
                Dock = DockStyle.Top
            };

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.Plus,
                Font = new Font("Segoe UI Emoji", 20),
                ForeColor = Color.White,
                Location = new Point(20, 15),
                AutoSize = true
            };

            Label titleLabel = new Label
            {
                Text = "医疗卡充值",
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.White,
                Location = new Point(60, 18),
                AutoSize = true
            };

            headerPanel.Controls.Add(lblTitleIcon);
            headerPanel.Controls.Add(titleLabel);

            // 创建主面板
            mainPanel = new Panel
            {
                Size = new Size(460, 260),
                Location = new Point(20, 80),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            CreateRechargeArea();

            // 创建底部按钮面板
            bottomPanel = new Panel
            {
                Size = new Size(500, 60),
                BackColor = Color.FromArgb(240, 240, 240),
                Dock = DockStyle.Bottom
            };

            CreateBottomButtons();

            // 添加面板到窗体
            this.Controls.Add(headerPanel);
            this.Controls.Add(bottomPanel);
            this.Controls.Add(mainPanel);
        }

        private void CreateRechargeArea()
        {
            // 卡号显示
            Label lblCardNoTitle = new Label
            {
                Text = "就诊卡号:",
                Font = new Font("微软雅黑", 12),
                Location = new Point(30, 30),
                Size = new Size(80, 25)
            };

            lblCardNo = new Label
            {
                Text = cardNo,
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(120, 30),
                Size = new Size(200, 25),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 当前余额显示
            Label lblBalanceTitle = new Label
            {
                Text = "当前余额:",
                Font = new Font("微软雅黑", 12),
                Location = new Point(30, 70),
                Size = new Size(80, 25)
            };

            lblCurrentBalance = new Label
            {
                Text = "查询中...",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(120, 70),
                Size = new Size(200, 25),
                ForeColor = Color.Green
            };

            // 充值金额
            Label lblAmountTitle = new Label
            {
                Text = "充值金额:",
                Font = new Font("微软雅黑", 12),
                Location = new Point(30, 110),
                Size = new Size(80, 25)
            };

            txtRechargeAmount = new TextBox
            {
                Location = new Point(120, 105),
                Size = new Size(150, 30),
                Font = new Font("微软雅黑", 12)
            };

            Label lblYuan = new Label
            {
                Text = "元",
                Font = new Font("微软雅黑", 12),
                Location = new Point(280, 110),
                Size = new Size(20, 25)
            };

            // 支付方式
            Label lblPayTitle = new Label
            {
                Text = "支付方式:",
                Font = new Font("微软雅黑", 12),
                Location = new Point(30, 150),
                Size = new Size(80, 25)
            };

            cmbPayChannel = new ComboBox
            {
                Location = new Point(120, 145),
                Size = new Size(150, 30),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("微软雅黑", 12)
            };
            cmbPayChannel.Items.AddRange(new string[] { "现金", "银行卡", "支付宝", "微信支付" });
            cmbPayChannel.SelectedIndex = 0;

            // 结果显示
            lblResult = new Label
            {
                Location = new Point(30, 190),
                Size = new Size(400, 50),
                Font = new Font("微软雅黑", 10),
                ForeColor = Color.Gray,
                Text = "请输入充值金额并选择支付方式"
            };

            mainPanel.Controls.AddRange(new Control[] {
                lblCardNoTitle, lblCardNo, lblBalanceTitle, lblCurrentBalance,
                lblAmountTitle, txtRechargeAmount, lblYuan,
                lblPayTitle, cmbPayChannel, lblResult
            });
        }

        private void CreateBottomButtons()
        {
            // 充值按钮
            btnRecharge = IconManager.CreateSmallIconButton("确认充值", IconManager.Icons.Save, 120, 40, ButtonStyle.Success);
            btnRecharge.Location = new Point(150, 10);

            // 取消按钮
            btnCancel = IconManager.CreateSmallIconButton("取消", IconManager.Icons.Close, 100, 40, ButtonStyle.Danger);
            btnCancel.Location = new Point(290, 10);

            bottomPanel.Controls.Add(btnRecharge);
            bottomPanel.Controls.Add(btnCancel);
        }

        private void SetupEventHandlers()
        {
            btnRecharge.Click += BtnRecharge_Click;
            btnCancel.Click += BtnCancel_Click;
            txtRechargeAmount.TextChanged += TxtRechargeAmount_TextChanged;
        }

        private async void LoadCardInfo()
        {
            try
            {
                // 这里可以调用API获取当前卡余额
                // 暂时模拟显示
                await Task.Delay(500);
                lblCurrentBalance.Text = "¥0.00"; // 可以从API获取实际余额
            }
            catch (Exception ex)
            {
                lblCurrentBalance.Text = "查询失败";
                lblCurrentBalance.ForeColor = Color.Red;
            }
        }

        private void TxtRechargeAmount_TextChanged(object sender, EventArgs e)
        {
            if (decimal.TryParse(txtRechargeAmount.Text, out decimal amount) && amount > 0)
            {
                lblResult.Text = $"充值 ¥{amount:F2}，充值后余额将增加 ¥{amount:F2}";
                lblResult.ForeColor = Color.Green;
                btnRecharge.Enabled = true;
            }
            else
            {
                lblResult.Text = "请输入有效的充值金额";
                lblResult.ForeColor = Color.Red;
                btnRecharge.Enabled = false;
            }
        }

        private async void BtnRecharge_Click(object sender, EventArgs e)
        {
            if (!decimal.TryParse(txtRechargeAmount.Text, out decimal amount) || amount <= 0)
            {
                MessageBox.Show("请输入有效的充值金额", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (amount > 10000)
            {
                MessageBox.Show("单次充值金额不能超过¥10,000", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var confirmMessage = $"确认充值信息：\n\n" +
                               $"就诊卡号：{cardNo}\n" +
                               $"充值金额：¥{amount:F2}\n" +
                               $"支付方式：{cmbPayChannel.Text}\n\n" +
                               $"是否确认充值？";

            if (MessageBox.Show(confirmMessage, "确认充值", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                await ProcessRecharge(amount);
            }
        }

        private async Task ProcessRecharge(decimal amount)
        {
            try
            {
                btnRecharge.Enabled = false;
                btnRecharge.Text = "充值中...";
                lblResult.Text = "正在处理充值，请稍候...";
                lblResult.ForeColor = Color.Blue;

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var rechargeData = new
                    {
                        cardNo = cardNo,
                        amount = amount,
                        payChannel = cmbPayChannel.Text,
                        operatorId = currentUserId
                    };

                    var json = JsonConvert.SerializeObject(rechargeData, Formatting.Indented);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    string url = "http://101.201.170.32:5115/api/DoctorWorkstation/recharge-card";
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"充值请求: {json}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200 && apiResponse?.data != null)
                        {
                            var data = apiResponse.data;
                            string successMessage = "充值成功！\n\n";
                            
                            if (data.beforeBalance != null)
                                successMessage += $"充值前余额：¥{data.beforeBalance:F2}\n";
                            if (data.rechargeAmount != null)
                                successMessage += $"充值金额：¥{data.rechargeAmount:F2}\n";
                            if (data.afterBalance != null)
                                successMessage += $"充值后余额：¥{data.afterBalance:F2}\n";
                            if (data.rechargeTime != null)
                                successMessage += $"充值时间：{data.rechargeTime}\n";

                            MessageBox.Show(successMessage, "充值成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            string errorMessage = apiResponse?.msg?.ToString() ?? "充值失败";
                            MessageBox.Show(errorMessage, "充值失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            lblResult.Text = errorMessage;
                            lblResult.ForeColor = Color.Red;
                        }
                    }
                    else
                    {
                        string errorMessage = $"充值失败: {response.StatusCode}";
                        MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        lblResult.Text = errorMessage;
                        lblResult.ForeColor = Color.Red;
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMessage = $"网络请求失败: {ex.Message}";
                MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblResult.Text = errorMessage;
                lblResult.ForeColor = Color.Red;
            }
            finally
            {
                btnRecharge.Enabled = true;
                btnRecharge.Text = "确认充值";
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
} 